package com.san.base.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.druid.pool.DruidPooledConnection;
import com.san.common.datasource.JdbcConnectionPool;
import com.san.common.datasource.JdbcEntity;
import com.san.common.utils.AESUtils;
import com.san.common.utils.Constant;
import com.san.metadata.domain.DataSourceDO;
import com.san.metadata.service.DataSourceService;
import com.san.metadata.vo.DataSourceVO;

@Service
public class BaseManager {

	@Autowired
	protected DataSourceService dataSourceService;

	@Autowired
	protected JdbcConnectionPool jdbcConnectionPool;

	// 批量提交条数，集合需迭代处理
	protected static final int COMMIT_SIZE_FOREACH = 100;

	// 批量提交条数
	protected static final int COMMIT_SIZE = 500;

	/**
	 * 构建JDBC连接属性
	 * 
	 * @param dataSourceVO
	 * @return
	 */
	public JdbcEntity buildJdbcEntity(DataSourceVO dataSourceVO) {
		JdbcEntity entity = new JdbcEntity();
		entity.setSourceType(dataSourceVO.getSourceType());
		entity.setIp(dataSourceVO.getIpAddress());
		entity.setPort(dataSourceVO.getPort());
		entity.setDbName(dataSourceVO.getDbName());
		entity.setUser(dataSourceVO.getDbUser());
		entity.setPassword(AESUtils.AESDecode(Constant.DATA_SOURCE_KEY, dataSourceVO.getDbPassword()));

		return entity;
	}

	/**
	 * 构建JDBC连接属性
	 * 
	 * @param dataSourceDO
	 * @return
	 */
	public JdbcEntity buildJdbcEntity(DataSourceDO dataSourceDO) {
		JdbcEntity entity = new JdbcEntity();
		entity.setSourceType(dataSourceDO.getSourceType());
		entity.setIp(dataSourceDO.getIpAddress());
		entity.setPort(dataSourceDO.getPort());
		entity.setDbName(dataSourceDO.getDbName());
		entity.setUser(dataSourceDO.getDbUser());
		entity.setPassword(AESUtils.AESDecode(Constant.DATA_SOURCE_KEY, dataSourceDO.getDbPassword()));

		return entity;
	}
	
	/**
	 * 获取JDBC连接池连接
	 * 
	 * @param dataSourceCode
	 * @return
	 * @throws Exception
	 */
	protected DruidPooledConnection getBaseDBConnection() throws Exception {

		return this.getDBConnection(Constant.SOURCE_CODE_BASESOURCE);
	}

	/**
	 * 获取JDBC连接池连接
	 * 
	 * @param dataSourceCode
	 * @return
	 * @throws Exception
	 */
	protected DruidPooledConnection getDBConnection(String dataSourceCode) throws Exception {

		return jdbcConnectionPool.getDBConnection(dataSourceCode);
	}

}
